package cn.com.zzl.util;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * Description：zip压缩工具类
 * Created by 朱正磊 on 2017-05-22 14:10.
 */
public class ZipUtils {

	private final static int BUFFER = 2048;

	/**
	 * @Desc zip压缩
	 * @param fileNames 待压缩的多个文件名（全路径）
	 * @param outName 压缩目的文件名（全路径）
	 * @return 如果文件压缩成功返回true，压缩失败返回false
	 */
	public static boolean zip(String[] fileNames, String outName) throws IOException {
		boolean flag = true;
		try {
			BufferedInputStream origin ;//输入流缓冲器
			FileOutputStream dest = new FileOutputStream(outName);//文件输出流
			ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(dest));//zip输出流
			byte[] data = new byte[BUFFER];
			for(int i = 0; i < fileNames.length; i++){
				File file = new File(fileNames[i]);
				FileInputStream in = new FileInputStream(file);//文件输入流
				origin = new BufferedInputStream(in,BUFFER);//初始化输入流缓冲器
				ZipEntry entry = new ZipEntry(file.getName());//实例化zip入口
				zipOut.putNextEntry(entry);
				int count;
				while((count = origin.read(data, 0, BUFFER)) != -1){
					zipOut.write(data, 0, count);
				}
				origin.close();//关闭输入流缓冲器
			}
			zipOut.close();//关闭zip输出流
		} catch (FileNotFoundException e) {
			flag = false;
			e.printStackTrace();
			FileUtil.printExceptionInfo(e);
		}
		return flag;
	}

	/**
	 * @Desc 说明：文件路径的格式可以是E:\\xxx\\ttt.txt，也可以是e:/xxx/ttt.txt
	 * @param args
	 */
	public static void main(String[] args) throws IOException {
		String[] fileNames = new String[]{"E:\\zip\\hhhh.txt","E:\\zip\\file\\zzz.txt","E:/zip/file/yasuowj/xxx.txt"};
		//String outName = "e:/zip/sss/jimo.zip";//系统找不到指定的路径。
		String outName = "e:/zip/jimo.zip";//OK
		boolean flag = zip(fileNames,outName);
		System.out.println(flag);
	}

}
